import styles from "../../index.module.less";
import cs from "classnames";
import { map, find } from "lodash";
import { getAllCarList } from "@/api/modules/dashboard";
import { useRequest } from "ahooks";
import useUrl from "@/hooks/useUrl";

interface Props {
	realTimeMarkers?: any[];
}

export default (props: Props) => {
	const { realTimeMarkers = [] } = props;
	const { navigate } = useUrl();
	const { data: data } = useRequest(() => getAllCarList({}));
	const carData = data?.data;

	const handleGoCarDetail = (item: any) => {
		navigate(`/monitor/carDashboard?detailId=${item?.id}&vin=${item.vin}`, { state: item });
	};

	// 合并车辆数据和实时数据
	const getMergedCarData = () => {
		if (!carData) return [];

		return carData.map((car: any) => {
			// 查找对应的实时数据
			const realTimeData = find(
				realTimeMarkers,
				(marker: any) =>
					marker.vehicleInfo?.vin === car.vin || marker.vehicleInfo?.plateNo === car.plateNo || marker.id === car.id
			);

			// 判断是否在线：有实时数据且有位置信息
			const isOnline = realTimeData && realTimeData.position && realTimeData.position.length === 2;

			// 状态判断：优先判断是否有任务，然后判断在线状态
			let status = "space"; // 默认离线
			let statusText = "离线";

			// 优先使用实时数据中的 taskStatus 判断任务状态
			const taskStatus = realTimeData?.vehicleInfo?.taskStatus;
			if (taskStatus === 1) {
				status = "tasking";
				statusText = "任务中";
			} else if (isOnline) {
				status = "tasking";
				statusText = "在线";
			}

			return {
				...car,
				isOnline,
				realTimeData: realTimeData?.vehicleInfo || null,
				speed: realTimeData?.vehicleInfo?.speed || 0,
				soc: realTimeData?.vehicleInfo?.soc || 0,
				status,
				statusText
			};
		});
	};

	const mergedCarData = getMergedCarData();

	return (
		<div className={cs(styles.car, styles.commonBox)}>
			<div className={styles.moduleHeader}>
				<div className={cs(styles.icon, styles.iconCar)}></div>
				<div className={styles.title}>车辆统计</div>
			</div>
			<div className={styles.filterForm}></div>
			<div className={styles.carList}>
				{map(mergedCarData, (item: any, index: number) => {
					return (
						<div
							className={cs(styles.carItem, item.status === "tasking" ? styles.tasking : styles.space, false && styles.charge)}
							onClick={() => handleGoCarDetail(item)}
							key={index}
						>
							<div className={styles.name}>{item.plateNo}</div>
							<div className={styles.info}>
								<div className={styles.type}>自动驾驶</div>
								<div className={styles.other}>
									<div className={styles.icon}></div>
									<div className={styles.name}>{Number(item.speed).toFixed(2)}km/h</div>
								</div>
							</div>
							<div className={styles.status}>{item.statusText}</div>
						</div>
					);
				})}
			</div>
		</div>
	);
};
